package com.zjitc.book.filter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWT;
import com.zjitc.book.entity.MyUserDetails;
import com.zjitc.book.service.impl.UserServiceImpl;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class JwtFilter extends OncePerRequestFilter {

    @Autowired
    AuthenticationManager authenticationManager;

    @Autowired
    UserServiceImpl userDetailsService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //Authorization---->"Bearer xxxxxxxxxxxxxxx"
        String authHeader = request.getHeader("Authorization");
        if(StrUtil.isNotBlank(authHeader) && authHeader.startsWith("Bearer  ")){
            String token = authHeader.substring(7);
            //1.解密token
            JWT jwt = JWT.of(token).setKey("1234567890abcdef".getBytes());
            //2.验证令牌有效性
            if(jwt.verify()){
                //3.如果jwt令牌有效，那么输出放进去的userid,就可以找到该用户的信息
                String  username = (String) jwt.getPayload("username");
                String  userid = (String) jwt.getPayload("userid");
//                MyUserDetails userDetails = (MyUserDetails) userDetailsService.loadUserByUsername(username);
                Set<String> auths = stringRedisTemplate.opsForSet().members("user:perms" + userid);
                List<SimpleGrantedAuthority> authors = new ArrayList<>();
                auths.forEach(auth->authors.add(new SimpleGrantedAuthority(auth)));

                //4.再让springsecurity接管
                UsernamePasswordAuthenticationToken authenticationToken =
                        new UsernamePasswordAuthenticationToken(username,null,authors);
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        }
        //放行请求
        filterChain.doFilter(request,response);

    }
}








